package com.bao.grpc.files.service.impl;



import java.io.File;
import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import com.bao.grpc.files.service.FilesService;



/**
 * <p>
 *  服务实现类
 * </p>
 * 
 * @author bao
 */
@Service
public class FilesServiceImpl implements FilesService {

	@Override
    public String fileUpload(File file) {
        CloseableHttpClient client = null;
        String result = null;
        try {
            client = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost("https://api.xintujing.cn/v1/upload/website/file");
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            //addTextBody(String,String)该方法可以传入参数，例如请求的地址需要接受一个id
            //builder.addTextBody("id", "1");
            builder.addTextBody("bucketName", "qywx");
            //addBinaryBody()该方法传入二进制内容，可以传入InputStream，File, 参数三是传入的类型，参数四是文件名称
            builder.addBinaryBody("file", file , ContentType.MULTIPART_FORM_DATA, file.getName());
            httpPost.setEntity(builder.build());
            HttpResponse response = client.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                // 取回服务器端的响应结果
                 result = EntityUtils.toString(response.getEntity(), "utf-8");
                 return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
            	file.delete();
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
